package com.zhq.zhq_blog.module.setting.fragment;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.zhq.zhq_blog.R;
import com.zhq.zhq_blog.base.BaseFragment;
import com.zhq.zhq_blog.base.Constant;
import com.zhq.zhq_blog.databinding.FragmentSettingsBinding;

import java.util.Objects;

public class SettingsFragment extends BaseFragment {

    private FragmentSettingsBinding mViewBinding;

    protected AppCompatActivity context;
    protected Toolbar toolbar;
    protected String toolbarTitle;
    private PreferenceFragmentCustom preferenceFragmentCustom;

    protected boolean setDisplayHomeAsUpEnabled = true;

    public void initView() {
        toolbarTitle = "设置";
        toolbar = mViewBinding.toolbar;
        toolbar.setTitle(toolbarTitle);
        context.setSupportActionBar(toolbar);
        if (setDisplayHomeAsUpEnabled) {
            Objects.requireNonNull(context.getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        }
        if (preferenceFragmentCustom==null){
            preferenceFragmentCustom = new PreferenceFragmentCustom();
        }
        if (!preferenceFragmentCustom.isAdded()){
            FragmentManager manager = getChildFragmentManager();
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(R.id.pref_container, preferenceFragmentCustom, "preference");
            ft.commit();
        }
    }

    @NonNull
    @Override
    protected View createView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container) {
        mViewBinding = FragmentSettingsBinding.inflate(inflater,container,false);
        context = (AppCompatActivity) getActivity();
        initView();
        return mViewBinding.getRoot();
    }

    @Override
    protected void onLazyLoad() {

    }

    public static class PreferenceFragmentCustom extends PreferenceFragmentCompat {
        private AppCompatActivity context;

        @Override
        public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
            setPreferencesFromResource(R.xml.preferences, rootKey);
            context = (AppCompatActivity) getContext();
            settingPreferences();
        }

        /**
         * Preference item setting
         */
        public void settingPreferences() {

            // update preference setting, setting version name and version code
            String versionName = "";
            int versionCode = 1;
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                        context.getPackageName(), 0);
                versionName = packageInfo.versionName;
                versionCode = packageInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(getClass().getName(), e.getMessage());
                e.printStackTrace();
            }
            // set version name and version code for preference item's summary
            Preference versionPref = findPreference("check_update");
            String appVersionText = getResources().getString(R.string.app_version_text);
            versionPref.setSummary(appVersionText + " " + versionName
                    + " ( " + versionCode + " ) ");

            // feedback
            Preference feedbackPref = findPreference("feedback");
            feedbackPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Intent intent = new Intent(Intent.ACTION_SENDTO);
                    intent.setData(Uri.parse("mailto:" + Constant.MY_EMAIL));
                    String subject = getResources().getString(R.string.pref_title_feedback);
                    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
                    startActivity(intent);
                    return true;
                }
            });

            // App rating
            Preference ratingPref = findPreference("rating");
            ratingPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String packageName = context.getPackageName();
                    intent.setData(Uri.parse("market://details?id=" + packageName));
                    startActivity(intent);
                    return true;
                }
            });

            // check update
            Preference updatePref = findPreference("check_update");
            updatePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    // check update
                    return false;
                }
            });

            // About preference setting, open AboutFragment on preference click
            Preference aboutPref = findPreference("about");
            aboutPref.setOnPreferenceClickListener(
                    preference -> {
                        context.getSupportFragmentManager().beginTransaction()
                                .replace(R.id.fragment_container, new AboutFragment())
                                .addToBackStack(null)
                                .commit();
                        return true;
                    });
        }
    }
}
